<?php

class AdminController extends Zend_Controller_Action
{

    public function init()
    {
        $this->_helper->layout->setLayout('admin');
        
        $auth = Zend_Auth::getInstance();
        
        $requestParams = $this->getRequest()->getParams();
        if (!$auth->hasIdentity() && $requestParams['action'] != 'login') {
            $this->_redirect($this->view->url(array(), 'login'));
        }
    }

    public function indexAction()
    {
        //Zend_Debug::dump(Zend_Auth::getInstance()->getIdentity());
    }

    public function loginAction()
    {
        $form = new Application_Form_Login;
        $users = new Application_Model_DbTable_Users;
        
        $this->view->form = $form;
        
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $data = $form->getValues();
                
                if ($users->loginUser($data['username'], $data['password'])) {
                    $this->_redirect($this->view->url(array(), 'admin_index'));
                } else {
                    $this->view->message = 'Неверные логин или пароль.';
                }
            }
        }
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
    }

    public function pictureAction()
    {
        $form = new Application_Form_Image;
        $this->view->form = $form;
        
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $fileName = Application_Model_Img::saveImage($form);
                
                if ($fileName) {
                    $img = new Application_Model_DbTable_Photos;
                    
                    $rez = $img->saveSrcImage($fileName, $form->type_picture->getValue());
                    
                    if ($rez) {
                        $this->view->message = 'Фотография успешно сохранена';
                    }
                }
            }
        }
    }
    
    public function deleteAction()
    {
        $page = $this->getRequest()->getParam('page');
        
        $img = new Application_Model_DbTable_Photos;
        
        $images = $img->getAllImage();
        
        $paginator = Zend_Paginator::factory($images);
        
        $paginator->setItemCountPerPage(16);
        $paginator->SetCurrentPageNumber($page);
        
        $this->view->images = $paginator;
    }

    public function deleteimageAction()
    {
        $id = $this->getRequest()->getParam('id');
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        
        $img = new Application_Model_DbTable_Photos;
        $img->deleteImage($id);
        
        $this->_redirect($this->view->url(array(), 'admin_del'));
    }
}







